package com.sztu.service;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.sztu.mapper.StudentMapper;
import com.sztu.pojo.Student;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class StudentServiceImpl implements StudentService{
    @Autowired
    StudentMapper studentMapper;
    @Override
    public List<Student> getAllStudent() {
        return studentMapper.getAllStudent();
    }

    @Override
    public List<Student> queryStudent(Map map) {
        return studentMapper.queryStudent(map);
    }

    @Override
    public int addStudent(Map map) {
        return studentMapper.addStudent(map);
    }

    @Override
    public int delStudentById(Integer id) {
        return studentMapper.delStudentById(id);
    }

    @Override
    public int updateStudent(Map map) {
        return studentMapper.updateStudent(map);
    }

    @Override
    public Workbook exportExcel() {
        List<Student> studentList=studentMapper.getAllStudent();
        Workbook workbook= ExcelExportUtil.exportExcel(new ExportParams("学生表","学生"),Student.class,studentList);
        return workbook;
    }

    @Override
    public Integer importExcel(File file) {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        List<Student> studentList = ExcelImportUtil.importExcel(file, Student.class, params);
        for (Student student:studentList){
            Map<String,Object> map=new HashMap<String,Object>();
            map.put("id",student.getId());
            map.put("name",student.getName());
            map.put("account",student.getAccount());
            map.put("authority",student.getAuthority());
            map.put("password",student.getPassword());
            map.put("cid",student.getCollege().getId());
            try {
                if(studentMapper.updateStudent(map)!=1){
                    studentMapper.addStudent(map);
                }
            }catch (Exception e){
                return 0;
            }
        }
        return 1;
    }
}
